package com.loan.service;
import java.util.Arrays;
import java.util.Map;

import com.jfinal.plugin.activerecord.Page;
import com.loan.enums.S;
import com.loan.model.Loan;
import com.loan.util.Money;

public class LoanService extends BaseService<Loan>{

	public Loan findOne(int userId) {
		return Loan.dao.findFirst("select * from loan where user_id=? order by create_time desc",userId);
	}
	
	public Loan findProcess(int userId) {
		return Loan.dao.findFirst("select * from loan where user_id=? and status<>? and status<>? order by create_time desc",userId,S.REPAY_SUCCESS,S.REJECT);
	}
	
	/**
	 * 分页信息
	 * @param map 
	 * @return 
	 */
	public Page<Loan> list(int page, int size, Map<String, String> map, String orderBy) {
		return Loan.dao.paginate(page, size, buildSql("loan",Arrays.asList("real_name", "status", "user_id", "create_time", "remittance_time", "cid", "mobile"),map, " order by "+orderBy));
	}
	
	/**
	 * 计算交易收益总额
	 */
	public double sumByLoan(int loanId) {
		Loan ln = Loan.dao.findFirst("select sum(amount) as total from loan where status='process' and loan_id=?",loanId);
		return Money.get(ln.getDouble("total"));
	}

	public long count(Integer userId) {
		Loan ln = Loan.dao.findFirst("select count(id) as count from loan where user_id=? and remittance_time is not null",userId);
		Loan ln2 = Loan.dao.findFirst("select count(id) as count from repay where is_divide=1 and user_id=?",userId);
		return Money.getLong(ln.get("count"))+Money.getLong(ln2.get("count"));
	}
}
